package work.linruchang.util;

import cn.hutool.core.util.StrUtil;
import work.linruchang.util.other.SFunction;
import work.linruchang.util.other.SerializedLambda;

import java.util.Optional;

/**
 * Lambda工具类
 *
 * @author LinRuChang
 * @version 1.0
 * @date 2021/01/23
 * @since 1.8
 **/
public class LambdaUtil {

    /**
     * 获取SFunction的目标反射类
     * @param sFunction
     * @return 返回的反射类型其实是T
     */
    public static <T,R> Class<?> getTagetClazz(SFunction<T, R> sFunction) {
        SerializedLambda serializedLambda = SerializedLambda.resolve(sFunction);
        return (Class<T>) serializedLambda.getInstantiatedType();
    }


    /**
     * 获取Bean的属性名 == 默认全部是驼峰格式
     * @param sFunction
     * @param <T>
     * @param <R>
     * @return
     */
    public static <T,R> String getFieldName(SFunction<T, R> sFunction) {
        SerializedLambda serializedLambda = SerializedLambda.resolve(sFunction);
        String implMethodName = serializedLambda.getImplMethodName();
        return Optional.ofNullable(implMethodName)
                .map(methodName -> {
                    String fieldName = StrUtil.lowerFirst(StrUtil.subAfter(methodName, "get", false));
                    return fieldName;
                }).orElseThrow(() ->  new RuntimeException("Lambda解析出错，请检查"));
    }

    /**
     * 获取数据列名 == 默认数据库全部是下划线格式
     * @param sFunction
     * @param <T>
     * @param <R>
     * @return
     */
    public static <T,R> String getDBColumnName(SFunction<T, R> sFunction) {
        String fieldName = getFieldName(sFunction);
        return StrUtil.toUnderlineCase(fieldName);
    }




}
